import random

from models.llm_info import LLMInfo

from database.platform_repo import select_all_model_and_platform

from api.weibo import get_fans_list_api

from services.user_service import user_info_service

from utils.print_message import print_message

# 一页20粉丝, 我们要找20个粉丝，每一页拿1个粉丝进行抽查
def get_random_fans(user_id, cookie, analyse_user = 20):
    # 一页粉丝数量20个
    page_fans_count = 20
    # 1.获取用户的基本信息，拿到总的粉丝数
    res = user_info_service(user_id, cookie)
    if res == None:
        return None
    total_fans = res['followers_count']
    
    
    max_page = min(total_fans // page_fans_count + 1, analyse_user)
    
    if max_page == 0:
        return None
    if max_page == 1:
        fans_data = get_fans_list_api(user_id, 1, cookie)
        fans_list = fans_data['users']
        id_list = []
        for item in fans_list:
            id_list.append(item['id'])
        return id_list
    
    
    fans_one_page = analyse_user // max_page
    remain = 0
    if analyse_user % max_page != 0:
        remain = analyse_user % max_page
    
    
    choose_fans_list = []
    for page in range(1, max_page + 1):
        # 2.获取粉丝列表
        fans_data = get_fans_list_api(user_id, page, cookie)
        # 如果没有关注博主可能为None
        if fans_data['ok'] == 0:
            return fans_data['msg']
        fans_list = fans_data['users']
        if fans_list == None or len(fans_list) == 0:
            continue
        id_list = []
        for item in fans_list:
            id_list.append(item['id'])
        print_message(f"id_list:{id_list}, fans_one_page:{fans_one_page}, remain:{remain}")
        # 3.随机抽取粉丝
        if remain != 0:
            random_choice_num = min(len(id_list), fans_one_page + 1)
            random_fans = random.sample(id_list, random_choice_num)
            remain -= 1
        else:
            random_choice_num = min(len(id_list), fans_one_page)
            random_fans = random.sample(id_list, random_choice_num)
        choose_fans_list += random_fans
        if len(choose_fans_list) >= 20:
            break
    return choose_fans_list
